export function throttle(fn, limit) {
    let lastFunc;
    let lastRan;
    return function (...args) {
        if (!lastRan) {
            fn.apply(this, args);
            lastRan = Date.now();
        } else {
            clearTimeout(lastFunc);
            lastFunc = setTimeout(function () {
                if ((Date.now() - lastRan) >= limit) {
                    fn.apply(this, args);
                    lastRan = Date.now();
                }
            }, limit - (Date.now() - lastRan));
        }
    };
}
export function debounce(fn, delay) {
    let timer;
    return function (...args) {
        clearTimeout(timer);
        timer = setTimeout(() => {
            fn.apply(this, args);
        }, delay);
    };
}


export class ThrottleCacheControl {
    constructor(options = {}) {
        this.cache = {
            data: null,
            timestamp: null,
            key: null,
        };

        this.throttle = {
            timer: null,
            promise: null,
        };

        // 可配置的选项，使用传入的选项或默认值
        this.options = {
            throttleDelay: options.throttleDelay || 2000,
            cacheDuration: options.cacheDuration || 5 * 60 * 1000,
            cacheKeyGenerator: options.cacheKeyGenerator || this.defaultCacheKeyGenerator,
            dataProcessor: options.dataProcessor || (data => data),
        };
    }

    // 默认的缓存键生成器
    defaultCacheKeyGenerator(params) {
        return Object.entries(params)
            .sort(([keyA], [keyB]) => keyA.localeCompare(keyB))
            .map(([key, value]) => `${key}_${value}`)
            .join('_');
    }

    // 检查缓存是否有效
    isCacheValid(cacheKey) {
        const { cache } = this;
        const now = Date.now();

        return (
            cache.data &&
            cache.key === cacheKey &&
            cache.timestamp &&
            (now - cache.timestamp) < this.options.cacheDuration
        );
    }

    // 更新缓存
    updateCache(data, cacheKey) {
        const { cache } = this;
        cache.data = data;
        cache.timestamp = Date.now();
        cache.key = cacheKey;
    }

    // 清除节流状态
    clearThrottle() {
        const { throttle } = this;
        if (throttle.timer) {
            clearTimeout(throttle.timer);
        }
        throttle.promise = null;
        throttle.timer = null;
    }

    // 清除缓存
    clearCache() {
        this.cache.data = null;
        this.cache.timestamp = null;
        this.cache.key = null;
        this.clearThrottle();
    }

    // 处理请求
    async request(params, apiCall) {
        if (!apiCall || typeof apiCall !== 'function') {
            throw new Error('API调用函数是必需的');
        }

        const cacheKey = this.options.cacheKeyGenerator(params);

        // 检查缓存
        if (this.isCacheValid(cacheKey)) {
            return this.cache.data;
        }

        // 检查是否有相同参数的请求正在进行
        if (this.throttle.promise && this.throttle.timer) {
            return this.throttle.promise;
        }

        // 创建新的节流请求
        this.throttle.promise = new Promise(async (resolve, reject) => {
            try {
                // 发起API请求
                const response = await apiCall(params);
                const processedData = this.options.dataProcessor(response);

                // 更新缓存
                this.updateCache(processedData, cacheKey);
                resolve(processedData);

                // 设置节流定时器
                this.throttle.timer = setTimeout(() => {
                    this.clearThrottle();
                }, this.options.throttleDelay);
            } catch (error) {
                this.clearThrottle();
                reject(error);
            }
        });

        return this.throttle.promise;
    }
}
